package com.rtx.edi.platform.express.auth.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rtx.edi.model.express.auth.dto.PlAuthShopAppDto;
import com.rtx.edi.model.express.auth.po.PlAuthShopApp;
import com.rtx.edi.model.response.EdiResponse;
import com.rtx.edi.platform.express.auth.service.PlAuthShopAppService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 店铺应用绑定关系
 * @author luoqiongli
 *
 */
@Api(tags = {"店铺应用绑定关系"})
@RestController
@RequestMapping("/v1/plAuthShopApp")
public class PlAuthShopAppController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private PlAuthShopAppService plAuthShopAppService;
	
	@ApiOperation(value = "店铺应用绑定关系列表", notes = "分页获取店铺应用绑定关系")
    @PostMapping("qryPlAuthShopAppList")
	public EdiResponse qryPlAuthShopApp(@RequestBody PlAuthShopAppDto dto) {
		PlAuthShopApp shopapp=new PlAuthShopApp();
		BeanUtils.copyProperties(dto,shopapp);
		Page<PlAuthShopApp> pageParam = new Page<>(dto.getPageNum(),dto.getPageSize());
		plAuthShopAppService.selectPlAuthShopApp(pageParam,shopapp);
		return EdiResponse.success().data("page",pageParam);
	}
	
	@ApiOperation(value = "查询店铺应用绑定关系", notes = "查询店铺应用绑定关系")
    @PostMapping("qryPlAuthShopAppById")
	public EdiResponse qryPlAuthShopAppById(@RequestBody PlAuthShopAppDto dto) {
		
		return EdiResponse.success().data("item",plAuthShopAppService.getById(dto.getId()));
	}
	
	@ApiOperation(value = "新增店铺应用绑定关系", notes = "新增店铺应用绑定关系")
    @PostMapping("addPlAuthShopApp")
	public EdiResponse addPlAuthShopApp(@RequestBody PlAuthShopAppDto dto) {
		checkField(dto);
		QueryWrapper<PlAuthShopApp> qw=new QueryWrapper<PlAuthShopApp>();
		qw.eq("shopid", dto.getShopid())
		.eq("deleteflag","0")
		.eq("appid",dto.getAppid());
		boolean exists=plAuthShopAppService.getBaseMapper().exists(qw);
		if(exists) {
			return EdiResponse.failed().returnMgr("店铺应用绑定关系已存在不允许重复创建");
		}
		PlAuthShopApp shopapp=new PlAuthShopApp();
		BeanUtils.copyProperties(dto,shopapp);
		shopapp.setAddwho("ris_edi_dev");
		shopapp.setEditwho("ris_edi_dev");
		return plAuthShopAppService.addPlAuthShopApp(shopapp)?EdiResponse.success():EdiResponse.failed();
		
	}
	
	@ApiOperation(value = "修改店铺应用绑定关系", notes = "修改店铺应用绑定关系")
    @PostMapping("updPlAuthShopApp")
	public EdiResponse updPlAuthShopApp(@RequestBody PlAuthShopAppDto dto) {
		checkField(dto);
		PlAuthShopApp old=plAuthShopAppService.getById(dto.getId());
		if("1".equals(old.getActive())) {
			return EdiResponse.failed().returnMgr("已经启用则不允许修改");
		}
		PlAuthShopApp shopapp=new PlAuthShopApp();
		BeanUtils.copyProperties(dto,shopapp);
		shopapp.setEditwho("ris_edi_dev");
		shopapp.setEditdate(LocalDateTime.now());
		return plAuthShopAppService.updateById(shopapp)?EdiResponse.success():EdiResponse.failed();
	}
	
	@ApiOperation(value = "删除店铺应用绑定关系", notes = "删除店铺应用绑定关系")
    @PostMapping("delPlAuthShopAppByIds")
	public EdiResponse delPlAuthShopAppByIds(@RequestBody List<PlAuthShopAppDto> list) {
		try {
			
			// plAuthShopAppService.delPlAuthShopApp(list);
			// 逻辑删除 
			for (PlAuthShopAppDto dto : list) {
				PlAuthShopApp old=plAuthShopAppService.getById(dto.getId());
				if("1".equals(old.getActive())) {
					return EdiResponse.failed().returnMgr("已经启用则不允许修改");
				}
				PlAuthShopApp shopapp=new PlAuthShopApp();
				BeanUtils.copyProperties(dto,shopapp);
				shopapp.setEditwho("ris_edi_dev");
				shopapp.setEditdate(LocalDateTime.now());
				shopapp.setDeleteflag("1");
				plAuthShopAppService.updateById(shopapp);
			}
			return EdiResponse.success();
		} catch (Exception e) {
			return EdiResponse.failed().returnMgr(e.getMessage());
		}
	}
	
	@ApiOperation(value = "发起授权", notes = "发起授权")
    @PostMapping("doAuthShopApp")
	public EdiResponse doAuthShopApp(@RequestBody List<PlAuthShopAppDto> list) {
		try {
			
			List<HashMap<String,String>> authlist=plAuthShopAppService.buildUrlAuthShopapp(list);
			return EdiResponse.success().data("authlist", authlist);
		} catch (Exception e) {
			return EdiResponse.failed().returnMgr(e.getMessage());
		}

	}
	
	@ApiOperation(value = "获取token", notes = "获取token")
    @PostMapping("getToken")
	public EdiResponse getToken(@RequestBody List<PlAuthShopAppDto> list) {
		try {
			
			plAuthShopAppService.getTokenShopapp(list);
			
			return EdiResponse.success();
		} catch (Exception e) {
			return EdiResponse.failed().returnMgr(e.getMessage());
		}

	}
	
	@ApiOperation(value = "授权回调", notes = "授权回调")
	@GetMapping("callback")
	public EdiResponse callback(HttpServletRequest req) {
		JSONObject obj=new JSONObject();
		String code=req.getParameter("code");
		String state=req.getParameter("state");
		if(null!=code) {
			obj.put("code", code);
		}
		if(null!=req.getParameter("state")) {
			obj.put("state", state);
		}else {
			return EdiResponse.failed();
		}
		// 
		Long id=Long.parseLong(state);
		PlAuthShopApp shopapp=plAuthShopAppService.getById(id);
		if(shopapp!=null) {
			shopapp.setAuthcode(code);
			plAuthShopAppService.updateById(shopapp);
		}
		
		return EdiResponse.success().data("para", obj);
	}
	
	@ApiOperation(value = "授权回调", notes = "授权回调")
	@GetMapping("callback/edi")
	public EdiResponse callbackedi(HttpServletRequest req) {
		JSONObject callbackData = new JSONObject();
		String code=req.getParameter("code");
		String state=req.getParameter("state");
		callbackData.put("回调code", code);
		callbackData.put("回调state", state);
		return EdiResponse.success().data("para", callbackData);
	}
	
	@ApiOperation(value = "删除店铺应用绑定关系", notes = "删除店铺应用绑定关系")
    @PostMapping("delPlAuthShopApp")
	public EdiResponse delPlAuthShopApp(@RequestBody PlAuthShopAppDto dto) {
		
		return plAuthShopAppService.removeById(dto.getId())?EdiResponse.success():EdiResponse.failed();
	}
	
	/**
	 * 校验 
	 * @param dto
	 */
	private void checkField(PlAuthShopAppDto dto) {
		 Assert.notNull(dto.getShopid(),"店铺Id不能为空");
		 Assert.notNull(dto.getAppid(),"应用Id不能为空");

	}

}
